package com.chushouya.product.service.api.impl;

import com.chushouya.common.support.Contexts;
import com.chushouya.product.dto.admin.skuevaluate.SkuEvaluateItemValueQuery;
import com.chushouya.product.dto.admin.productsku.ProductSkuDataDTO;
import com.chushouya.product.dto.api.evaluatedata.EvaluateDataRequestApiDTO;
import com.chushouya.product.dto.api.evaluatedata.EvaluateDataResultApiDTO;
import com.chushouya.product.dto.api.evaluate.EvaluateCodeParseResult;
import com.chushouya.product.dto.api.evaluate.EvaluateResultItemApiDTO;
import com.chushouya.product.dto.api.evaluate.EvaluateRuleDTO;
import com.chushouya.product.dto.api.evaluate.PriceCalculationResult;
import com.chushouya.product.service.api.EvaluateResultApiService;
import com.chushouya.manager.service.common.PartnerRuleService;
import com.chushouya.product.dao.entity.EvaluateLogEntity;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.dao.entity.ProductSkuEntity;
import com.chushouya.product.dao.entity.SkuEvaluateItemEntity;
import com.chushouya.product.dao.entity.SkuEvaluateItemValueEntity;
import com.chushouya.product.dao.repository.EvaluateLogRepository;
import com.chushouya.product.dao.repository.ProductRepository;
import com.chushouya.product.dao.repository.ProductSkuRepository;
import com.chushouya.product.dao.repository.SkuEvaluateItemRepository;
import com.chushouya.product.dao.repository.SkuEvaluateItemValueRepository;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EvaluateResultApiServiceImpl implements EvaluateResultApiService {
    
    @Resource
    private ProductSkuRepository productSkuRepository;
    
    @Resource
    private SkuEvaluateItemValueRepository skuEvaluateItemValueRepository;
    
    @Resource
    private SkuEvaluateItemRepository skuEvaluateItemRepository;
    
    @Resource
    private ProductRepository productRepository;
    
    @Resource
    private EvaluateLogRepository evaluateLogRepository;
    
    @Resource
    private PartnerRuleService partnerRuleService;
    
    @Override
    public EvaluateDataResultApiDTO evaluateResult(EvaluateDataRequestApiDTO request) {
        final Long productId = request.getProductId();
        final Long skuId = request.getSkuId();
        final String skuCode = request.getSkuCode();
        final String evaluateCode = request.getEvaluateCode();
        
        // 参数校验
        Check.notNull(productId, "商品ID不能为空");
        
        // 1. 根据productId获取商品信息
        ProductEntity product = getProductInfo(productId);
        
        // 2. 根据skuId取 productSku 里面对应的一条记录
        ProductSkuEntity productSku = getProductSku(skuId);
        
        // 3. 根据evaluateCode 从 p_sku_evaluate_item_value 取列表记录
        List<SkuEvaluateItemValueEntity> evaluateItemValues = getEvaluateItemValues(evaluateCode, productId);
        
        // 4. 计算最终价格和评估规则（包含合作商加价）
        final Long partnerId = Contexts.getHeaderContext().getPartnerId();
        PriceCalculationResult calculationResult = calculateFinalPriceWithRules(productSku, evaluateItemValues, partnerId);
        BigDecimal finalPrice = calculationResult.getFinalPrice();
        List<EvaluateRuleDTO> evaluateRules = calculationResult.getEvaluateRules();
        
        // 5. 构建评估项列表（包含evaluateCode解析的项和skuData中的项）
        List<EvaluateResultItemApiDTO> evaluateItems = buildEvaluateItems(evaluateItemValues, productSku);
        
        // 6. 构建完整的返回结果
        EvaluateDataResultApiDTO result = buildEvaluateResult(product, productSku, evaluateItemValues, finalPrice, evaluateItems);
        
        // 7. 保存估价日志
        saveEvaluateLog(request, result, product, productSku, evaluateItems, evaluateRules);
        
        log.info("evaluateResult response, productId: {}, skuId: {}, finalPrice: {}, evaluateItemsCount: {}", 
                productId, skuId, finalPrice, evaluateItems.size());
        
        return result;
    }
    /**
     * 获取商品信息
     */
    private ProductEntity getProductInfo(Long productId) {
        ProductEntity product = productRepository.selectByPrimaryKey(productId);
        Check.notNull(product, "商品不存在，productId: " + productId);
        return product;
    }
    
    /**
     * 获取ProductSku记录
     */
    private ProductSkuEntity getProductSku(Long skuId) {
        ProductSkuEntity productSku = productSkuRepository.selectByPrimaryKey(skuId);
        Check.notNull(productSku, "SKU记录不存在，skuId: " + skuId);
        return productSku;
    }
    
    /**
     * 构建评估项列表（包含evaluateCode解析的项和skuData中的项）
     */
    private List<EvaluateResultItemApiDTO> buildEvaluateItems(List<SkuEvaluateItemValueEntity> evaluateItemValues, ProductSkuEntity productSku) {
        List<EvaluateResultItemApiDTO> evaluateItems = new ArrayList<>();
        
        // 1. 先添加从productSku的skuData中解析出来的评估项（SKU基本属性）
        List<EvaluateResultItemApiDTO> skuDataItems = Jsons.parseArray(productSku.getSkuData(),EvaluateResultItemApiDTO.class);
        evaluateItems.addAll(skuDataItems);
        // 2. 再添加从evaluateCode解析出来的评估项（价格调整项）
        for (SkuEvaluateItemValueEntity itemValue : evaluateItemValues) {
            EvaluateResultItemApiDTO item = new EvaluateResultItemApiDTO();
            item.setAttrId(itemValue.getItemId());
            item.setAttrName(itemValue.getItemName());
            item.setValueId(itemValue.getValueId());
            item.setValueContent(itemValue.getValueName());
            
            evaluateItems.add(item);
        }
        
        log.info("构建评估项列表完成，skuData项: {}个，evaluateCode项: {}个，总计: {}个", 
                skuDataItems.size(), evaluateItemValues.size(), evaluateItems.size());
        return evaluateItems;
    }
    
    /**
     * 构建完整的评估结果
     */
    private EvaluateDataResultApiDTO buildEvaluateResult(ProductEntity product, ProductSkuEntity productSku, 
                                                        List<SkuEvaluateItemValueEntity> evaluateItemValues,
                                                        BigDecimal finalPrice, List<EvaluateResultItemApiDTO> evaluateItems) {
        EvaluateDataResultApiDTO result = Beans.copy(product, EvaluateDataResultApiDTO.class);
        
        // 估价信息
        result.setEvaluatePrice(finalPrice);
        result.setEvaluateItems(evaluateItems);
        
        // 生成估价ID（可以根据业务需求自定义格式）
        String evaluateId = generateEvaluateId(product.getProductId(), productSku.getSkuId());
        result.setEvaluateId(evaluateId);
        
        // 下周跌幅（可以根据业务逻辑计算，这里先设置为0）
        result.setNextWeekFallPrice(BigDecimal.ZERO);
        
        log.info("构建评估结果完成: productName={}, finalPrice={}, evaluateId={}", 
                product.getProductName(), finalPrice, evaluateId);
        
        return result;
    }
    
    /**
     * 生成估价ID
     */
    private String generateEvaluateId(Long productId, Long skuId) {
        // 格式：EVAL_时间戳_商品ID_SKUID
        long timestamp = System.currentTimeMillis();
        return String.format("EVAL_%d_%d_%d", timestamp, productId, skuId);
    }
    
    /**
     * 保存估价日志
     */
    private void saveEvaluateLog(EvaluateDataRequestApiDTO request, EvaluateDataResultApiDTO result, 
                                ProductEntity product, ProductSkuEntity productSku, 
                                List<EvaluateResultItemApiDTO> evaluateItems, List<EvaluateRuleDTO> evaluateRules) {
        final Long userId = Contexts.getUserContext().getUserId();
        final Long partnerId = Contexts.getHeaderContext().getPartnerId();
        final String platform = Contexts.getHeaderContext().getPlatform();
        try {
            EvaluateLogEntity evaluateLog = Beans.copy(product, EvaluateLogEntity.class);
            Date now = new Date();
            
            // 基本信息
            evaluateLog.setEvaluateId(result.getEvaluateId());
            
            // SKU信息
            evaluateLog.setSkuId(productSku.getSkuId());
            evaluateLog.setSkuCode(productSku.getSkuAttrCode());
            evaluateLog.setSkuName(productSku.getSkuName());

            evaluateLog.setOrderId(Numbers.LONG_ZERO); // 订单ID，暂时无订单信息
            evaluateLog.setUserId(userId); // 用户ID，暂时无用户信息
            
            // 估价信息
            evaluateLog.setEvaluatePrice(result.getEvaluatePrice());
            evaluateLog.setNextWeekFallPrice(result.getNextWeekFallPrice());
            evaluateLog.setEvaluateCode(request.getEvaluateCode());
            
            // 评估项JSON数据
            String evaluateItemJson = Jsons.toJsonString(evaluateItems);
            evaluateLog.setEvaluateItem(evaluateItemJson);
            
            // 评估规则JSON数据
            String evaluateRulesJson = Jsons.toJsonString(evaluateRules);
            evaluateLog.setEvaluateRules(evaluateRulesJson);
            
            evaluateLog.setPlatform(platform); 
            evaluateLog.setChannel("WEB"); 
            evaluateLog.setPartnerId(partnerId); 
            
            // 时间信息
            evaluateLog.setCreateTime(now);
            evaluateLog.setUpdateTime(now);
            // 保存到数据库
            evaluateLogRepository.insertSelective(evaluateLog);
            

                    
        } catch (Exception e) {
            log.error("保存估价日志失败: evaluateId={}, error={}", result.getEvaluateId(), e.getMessage(), e);
            // 不抛出异常，避免影响主流程
        }
    }
    
    /**
     * 根据evaluateCode解析并获取评估项值列表
     * evaluateCode格式: "100001:4267603,100014:4267600,100006:4267595"
     */
    private List<SkuEvaluateItemValueEntity> getEvaluateItemValues(String evaluateCode, Long productId) {
        if (Strings.isEmpty(evaluateCode)) {
            return new ArrayList<>();
        }
        
        // 1. 解析evaluateCode获取itemIds和valueIds
        EvaluateCodeParseResult parseResult = parseEvaluateCode(evaluateCode);
        List<Long> itemIds = parseResult.getItemIds();
        List<Long> valueIds = parseResult.getValueIds();
        
        // 2. 从p_sku_evaluate_item获取评估项列表（按sort排序）
        List<SkuEvaluateItemEntity> evaluateItems = getEvaluateItemsByItemIds(itemIds, productId);
        
        // 3. 根据valueIds获取评估项值列表，并按评估项的sort排序
        return getEvaluateItemValuesSortedByItem(valueIds, productId, evaluateItems);
    }
    
    /**
     * 解析evaluateCode获取itemIds和valueIds
     * @param evaluateCode 评估代码，格式: "itemId:valueId,itemId:valueId"
     * @return 解析结果包含itemIds和valueIds
     */
    private EvaluateCodeParseResult parseEvaluateCode(String evaluateCode) {
        List<Long> itemIds = new ArrayList<>();
        List<Long> valueIds = new ArrayList<>();
        
        if (Strings.isEmpty(evaluateCode)) {
            return new EvaluateCodeParseResult(itemIds, valueIds);
        }
        
        String[] evaluatePairs = evaluateCode.split(",");
        for (String pair : evaluatePairs) {
            if (Strings.isEmpty(pair)) {
                continue;
            }
            String[] parts = pair.split(":");
            if (parts.length == 2) {
                try {
                    Long itemId = Long.parseLong(parts[0].trim());
                    Long valueId = Long.parseLong(parts[1].trim());
                    itemIds.add(itemId);
                    valueIds.add(valueId);
                } catch (NumberFormatException e) {
                    log.warn("解析evaluateCode失败，格式错误: {}", pair, e);
                }
            } else {
                log.warn("evaluateCode格式错误，应为itemId:valueId格式: {}", pair);
            }
        }
        
        log.debug("解析evaluateCode完成: itemIds={}, valueIds={}", itemIds, valueIds);
        return new EvaluateCodeParseResult(itemIds, valueIds);
    }

    /**
     * 根据itemIds从p_sku_evaluate_item获取评估项列表（按sort排序）
     * @param itemIds 项目ID列表
     * @param productId 产品ID
     * @return 评估项列表，按sort排序
     */
    private List<SkuEvaluateItemEntity> getEvaluateItemsByItemIds(List<Long> itemIds, Long productId) {
        if (itemIds == null || itemIds.isEmpty()) {
            log.warn("itemIds列表为空，无法查询评估项");
            return new ArrayList<>();
        }
        
        // 查询该商品的评估项，按sort排序
        List<SkuEvaluateItemEntity> allItems = skuEvaluateItemRepository.selectListByProductId(productId);
        
        // 过滤出指定的itemIds，保持sort排序
        return allItems.stream()
                .filter(item -> itemIds.contains(item.getItemId()))
                .sorted(Comparator.comparing(SkuEvaluateItemEntity::getSort, Comparator.nullsLast(Comparator.naturalOrder())))
                .collect(Collectors.toList());
    }
    
    /**
     * 根据valueIds获取评估项值列表，并按评估项的sort排序
     * @param valueIds valueId列表
     * @param productId 产品ID
     * @param evaluateItems 评估项列表（已按sort排序）
     * @return 评估项值列表，按评估项sort排序
     */
    private List<SkuEvaluateItemValueEntity> getEvaluateItemValuesSortedByItem(List<Long> valueIds, Long productId, List<SkuEvaluateItemEntity> evaluateItems) {
        if (valueIds == null || valueIds.isEmpty()) {
            log.warn("valueIds列表为空，无法查询评估项值");
            return new ArrayList<>();
        }
        
        // 查询评估项值
        SkuEvaluateItemValueQuery query = new SkuEvaluateItemValueQuery();
        query.setProductId(productId);
        query.setSkuItemValueIdList(valueIds);
        List<SkuEvaluateItemValueEntity> allEvaluateItemValues = skuEvaluateItemValueRepository.selectList(query);
        
        // 创建itemId到sort的映射
        Map<Long, Integer> itemSortMap = evaluateItems.stream()
                .collect(Collectors.toMap(
                        SkuEvaluateItemEntity::getItemId,
                        item -> item.getSort() != null ? item.getSort() : Integer.MAX_VALUE,
                        (existing, replacement) -> existing
                ));
        
        // 按评估项的sort排序
        return allEvaluateItemValues.stream()
                .sorted(Comparator.comparing(
                        item -> itemSortMap.getOrDefault(item.getItemId(), Integer.MAX_VALUE)
                ))
                .collect(Collectors.toList());
    }
    
    /**
     * 计算最终价格并生成评估规则
     * basePrice + 所有评估项的value值 + 合作商加价
     */
    private PriceCalculationResult calculateFinalPriceWithRules(ProductSkuEntity productSku, List<SkuEvaluateItemValueEntity> evaluateItemValues, Long partnerId) {
        BigDecimal basePrice = productSku.getBasePrice();
        if (basePrice == null) {
            basePrice = BigDecimal.ZERO;
        }
        
        BigDecimal currentPrice = basePrice;
        List<EvaluateRuleDTO> evaluateRules = new ArrayList<>();
        
        // 处理每个评估项的价格调整
        for (SkuEvaluateItemValueEntity evaluateItem : evaluateItemValues) {
            BigDecimal value = evaluateItem.getValue();
            Integer calcType = evaluateItem.getCalcType();
            
            if (value == null || value.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            
            BigDecimal beforePrice = currentPrice;
            BigDecimal afterPrice;
            BigDecimal change;
            String ruleDetail;
            
            if (calcType != null && calcType == 1) {
                // 按百分比计算
                afterPrice = currentPrice.add(value);
                change = value;
                ruleDetail = String.format("选有【%s:%s】", evaluateItem.getValueName(), value);
            } else {
                // 按金额计算：直接加减
                afterPrice = currentPrice.add(value);
                change = value;
                ruleDetail = String.format("选有【%s:%s】", evaluateItem.getValueName(), value);
                log.debug("Amount adjustment: item={}, value={}", evaluateItem.getValueName(), value);
            }
            
            // 创建评估规则记录
            EvaluateRuleDTO rule = new EvaluateRuleDTO();
            rule.setRuleName(evaluateItem.getItemName() != null ? evaluateItem.getItemName() : "价格调整");
            rule.setRuleDetail(ruleDetail);
            rule.setBefore(beforePrice);
            rule.setAfter(afterPrice);
            rule.setChange(change);
            
            evaluateRules.add(rule);
            currentPrice = afterPrice;
        }
        
        // 检查最低回收价
        BigDecimal minRecyclePrice = productSku.getMinPrice();
        if (minRecyclePrice != null && currentPrice.compareTo(minRecyclePrice) < 0) {
            BigDecimal beforePrice = currentPrice;
            BigDecimal afterPrice = minRecyclePrice;
            BigDecimal change = minRecyclePrice.subtract(currentPrice);
            
            EvaluateRuleDTO minPriceRule = new EvaluateRuleDTO();
            minPriceRule.setRuleName("最低回收价");
            minPriceRule.setRuleDetail(String.format("估价低于最低回收价%s元", minRecyclePrice));
            minPriceRule.setBefore(beforePrice);
            minPriceRule.setAfter(afterPrice);
            minPriceRule.setChange(change);
            
            evaluateRules.add(minPriceRule);
            currentPrice = afterPrice;
        }
        
        // 计算合作商加价
        if (partnerId != null) {
            BigDecimal partnerMarkup = partnerRuleService.calculatePartnerMarkup(partnerId, currentPrice);
            if (partnerMarkup != null && partnerMarkup.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal beforePrice = currentPrice;
                BigDecimal afterPrice = currentPrice.add(partnerMarkup);
                
                EvaluateRuleDTO partnerRule = new EvaluateRuleDTO();
                partnerRule.setRuleName("渠道加价");
                partnerRule.setRuleDetail(String.format("渠道加价%s元", partnerMarkup));
                partnerRule.setBefore(beforePrice);
                partnerRule.setAfter(afterPrice);
                partnerRule.setChange(partnerMarkup);
                
                evaluateRules.add(partnerRule);
                currentPrice = afterPrice;
                
                log.info("应用渠道加价: partnerId={}, beforePrice={}, markup={}, afterPrice={}", 
                        partnerId, beforePrice, partnerMarkup, afterPrice);
            }
        }
        
        return new PriceCalculationResult(currentPrice, evaluateRules);
    }
}
